//
//  JXAddressAddController.m
//  JiaoX
//
//  Created by yinqy on 15/1/19.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXAddressAddController.h"
#import "LocationDao.h"
#import "SelfDataTool.h"
#import "AddressDbBean.h"


#define PROVINCE_COMPONENT  0
#define CITY_COMPONENT      1
#define AREA_COMPONENT  2

@interface JXAddressAddController ()<UITextFieldDelegate,UIScrollViewDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
{
    UIScrollView *_contentScroll;
    UITextField *_nameText;
    UITextField *_phoneText;
    UITextField *_locationText;
    UITextField *_detailText;
    
    UIButton *_saveBtn;
    
    UIPickerView *_pickerView;
    
    LocationDao *_locationDao;
    
    NSArray *_provincesArray;
    
    NSMutableArray *_cityArray;
    
    NSMutableArray *_areaArray;
    
}
@end

@implementation JXAddressAddController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"新增地址"];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleBordered target:self action:@selector(saveAndUseBtnClick)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];

    [self.view setBackgroundColor:[UIColor whiteColor]];
    _contentScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, JXScreenW, self.view.height-NavHeight)];
    [_contentScroll setDelegate:self];
    [_contentScroll setContentSize:CGSizeMake(JXScreenW, _contentScroll.height)];
    [self.view addSubview:_contentScroll];
    [self initView];
    
    if (self.addressDetails) {
        JXLog(@"%@",self.addressDetails);
        [self initData];
    }
}

-(void)initView{
    _nameText = [self getEdit:30 placeHolder:@"收件人姓名"];
    _phoneText = [self getEdit:CGRectGetMaxY(_nameText.frame)+15 placeHolder:@"手机号码"];
    _phoneText.keyboardType = UIKeyboardTypePhonePad;
    _locationText = [self getEdit:CGRectGetMaxY(_phoneText.frame)+15 placeHolder:@"省市区"];
    [_locationText setTag:1001];
    _detailText = [self getEdit:CGRectGetMaxY(_locationText.frame)+15 placeHolder:@"具体地址:请详细填写方便配送"];
    
//    _saveBtn = [[UIButton alloc]init];
//    [_saveBtn setFrame:CGRectMake(JXPublicInset, CGRectGetMaxY(_detailText.frame)+15, JXScreenW-JXPublicInset*2, 46)];
//    [_saveBtn setBackgroundImage:[UIImage resizedImage:@"btn_login_bg"] forState:UIControlStateNormal];
//    [_saveBtn.layer setCornerRadius:5];
//    [_saveBtn setTitle:@"保存并使用" forState:UIControlStateNormal];
//    [_saveBtn addTarget:self action:@selector(saveAndUseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//    [_contentScroll addSubview:_saveBtn];
    
    
    _locationDao = [[LocationDao alloc]init];
    _provincesArray = [NSArray arrayWithArray:[_locationDao getProvinces]];
    
    AddressDbBean *provbean = [_provincesArray firstObject];
    _cityArray = [NSMutableArray arrayWithArray:[_locationDao getCitys:provbean.provinceId]];
    
    AddressDbBean *citybean = [_cityArray firstObject];
    _areaArray = [NSMutableArray arrayWithArray:[_locationDao getAreas:citybean.cityId]];
    
    _pickerView = [[UIPickerView alloc]init];
    CGFloat pickerH = 162;
    if(iPhone6){
        pickerH = 216;
    }else if(iPhone5s){
        pickerH = 180;
    }
    [_pickerView setFrame:CGRectMake(0, self.view.height, JXScreenW, pickerH)];
    [_pickerView setDataSource:self];
    [_pickerView setDelegate:self];
    _pickerView.showsSelectionIndicator = YES;
    [_pickerView selectRow: 0 inComponent: 0 animated: YES];
    [self.view addSubview:_pickerView];
}

/**
 *  如果是修改地址，需要在这个地方将传进来的数据填充到界面上
 */
-(void)initData{
    _nameText.text = self.addressDetails.addressee;
    _phoneText.text= self.addressDetails.phoneCode;
    _locationText.text = [_locationDao getDetaild:self.addressDetails.provinceId :self.addressDetails.cityId :self.addressDetails.areaId :@"-"];
    _detailText.text = self.addressDetails.detailAdres;
}

-(void)saveAndUseBtnClick{
    //进行一系列的判空
    if([Utils isBlankString:_nameText.text] || [Utils isBlankString:_phoneText.text] || [Utils isBlankString:_locationText.text] || [Utils isBlankString:_detailText.text]){
        [DialogUtils showTipsWithView:self.navigationController.view String:@"请把信息填写完整!"];
        return;
    }
    
    if(![Utils isPhoneNumber:_phoneText.text]){
        [DialogUtils showTipsWithView:self.navigationController.view String:@"手机号码不合法"];
        return;
    }
    AddressDbBean *bean = [self setProvCityAreaText];
    MBProgressHUD *HUD = [DialogUtils showLoadingWithView:self.navigationController.view];
    
    NSString *addressId = self.addressDetails==nil?nil:self.addressDetails.addressId;
    JXLog(@"addressId=%@",addressId);
    [SelfDataTool addAddressWithAddressee:_nameText.text phoneCode:_phoneText.text provinceId:bean.provinceIdStr cityId:bean.cityIdStr areaId:bean.areaIdStr detailAdres:_detailText.text addressId:addressId success:^(JXBaseResponse *result) {
        [HUD hide:YES];
        if ([Utils isBlankString:result.data]) {
            [DialogUtils showTipsWithView:self.navigationController.view String:@"操作成功"];
            //添加成功
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
        }
    } failure:^(NSError *error) {
        [HUD hide:YES];
        [DialogUtils showTipsWithView:self.navigationController.view String:@"操作失败"];
    }];
}

-(UITextField *)getEdit:(CGFloat)y placeHolder:(NSString *)placeHolder{
    UITextField *field = [[UITextField alloc]init];
    [field setPlaceholder:placeHolder];
    [field setTextColor:[UIColor blackColor]];
    [field setFrame:CGRectMake(JXPublicInset, y, JXScreenW-JXPublicInset*2, 46)];
    //设置边框
    [field.layer setBorderColor:JXColor(204, 204, 204).CGColor];
    [field.layer setBorderWidth:0.7];
    [field.layer setCornerRadius:5];
    
    //输入框添加左边距
    CGRect frame = [field frame];
    frame.size.width = 7.0f;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    field.leftViewMode = UITextFieldViewModeAlways;
    field.leftView = leftview;
    [_contentScroll addSubview:field];
    field.delegate = self;
    return field;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if (textField.tag == 1001) {
        [self.view endEditing:YES];
        //弹出地址选择框
        [UIView animateWithDuration:0.4 animations:^{
            _pickerView.y = self.view.height-_pickerView.height;
        }];
        return NO;
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [self hidenPickerView:YES];
    [textField.layer setBorderColor:JXThemeColor.CGColor];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [textField.layer setBorderColor:JXColor(204, 204, 204).CGColor];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
    [self hidenPickerView:YES];
}

-(void)hidenPickerView:(BOOL)hiden{
    if(hiden){
        if (_pickerView.y!= self.view.height) {
            //弹出地址选择框
            [UIView animateWithDuration:0.4 animations:^{
                _pickerView.y = self.view.height;
            }];
        }
    }else{
        if (_pickerView.y!=self.view.height-_pickerView.height) {
            //弹出地址选择框
            [UIView animateWithDuration:0.4 animations:^{
                _pickerView.y = self.view.height-_pickerView.height;
            }];
        }
    }
}

#pragma UIPICKERVIEW DATASOURCE & DELEGATE 

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if(component==0){
        return _provincesArray.count;
    }else if(component == 1){
        return _cityArray.count;
    }else{
        return _areaArray.count;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    BOOL isSelectProv = NO;
    switch (component) {
        case PROVINCE_COMPONENT:{
            //更新市array
            AddressDbBean *provbean = _provincesArray[row];
            _cityArray = [NSMutableArray arrayWithArray:[_locationDao getCitys:provbean.provinceId]];
            
            [pickerView reloadComponent:CITY_COMPONENT];
            [pickerView selectRow:0 inComponent:CITY_COMPONENT animated:NO];
            isSelectProv = YES;
        }
        case CITY_COMPONENT:{
            //更新县array
            AddressDbBean *citybean = _cityArray[isSelectProv?0:row];
            _areaArray = [NSMutableArray arrayWithArray:[_locationDao getAreas:citybean.cityId]];
            [pickerView reloadComponent:AREA_COMPONENT];
            [pickerView selectRow:0 inComponent:AREA_COMPONENT animated:NO];
            break;
        }
        case AREA_COMPONENT:{
            break;
        }
    }
    
    [self setProvCityAreaText];
}

/**
 *  这个名字取得有点不好不要介意
 *
 *  @return
 */
-(AddressDbBean *)setProvCityAreaText{
    NSInteger provinceIndex = [_pickerView selectedRowInComponent: PROVINCE_COMPONENT];
    NSInteger cityIndex = [_pickerView selectedRowInComponent: CITY_COMPONENT];
    NSInteger areaIndex = [_pickerView selectedRowInComponent: AREA_COMPONENT];
    
    AddressDbBean *provBean = _provincesArray[provinceIndex];
    AddressDbBean *cityBean = _cityArray[cityIndex];
    AddressDbBean *areaBean = _areaArray[areaIndex];
    
    [_locationText setText:[NSString stringWithFormat:@"%@-%@-%@",provBean.provinceName,cityBean.cityName,areaBean.areaName]];
    
    provBean.cityId = cityBean.cityId;
    provBean.cityName = cityBean.cityName;
    provBean.areaId = areaBean.areaId;
    provBean.areaName = areaBean.areaName;
    
    return provBean;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    switch (component) {
        case PROVINCE_COMPONENT:{
            AddressDbBean *temp =  _provincesArray[row];
            return temp.provinceName;
            break;
        }
        case CITY_COMPONENT:{
            AddressDbBean *temp =  _cityArray[row];
            return temp.cityName;
            break;
        }
        case AREA_COMPONENT:{
            AddressDbBean *temp =  _areaArray[row];
            return temp.areaName;
            break;
        }
    }
    return @"";
}


-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

@end
